
<?php

 $accessToken = new ACCESSTOKEN("wx0beb599bd49a9d93","7e7094bf491bcdad600f2ed2bbdedc58");

   $access_token =  $accessToken->GetAccessToken();

       
class ACCESSTOKEN{
	
	private $appId;
	
	private $appSecret;
	
	public function __construct($appId, $appSecret){
		 
		$this->appId = $appId;
    
	   $this->appSecret = $appSecret;
	}
	
	public function GetAccessToken(){
		
		
		$data = json_decode($this->get_php_file("saestor://hcfile/access_token.json"));
		
		if($data->expire_time < time()){
			
	   // 如果是企业号用以下URL获取access_token
	   
      // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
	  
         $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
		 
	     $res = json_decode($this->httpGet($url));//获取了微信服务器返回的access_token的对象
		  
		 $access_token = $res->access_token;//将access_token赋给变量
		 
		 if($access_token){
			 
			$data->expire_time = time() + 7000;
            
			
			
			$data->access_token = $access_token;
            
			$this->set_php_file("saestor://hcfile/access_token.json", json_encode($data));//将第一个token值及周期写入本地服务器文本
		 }
            
		}else{
			
			$access_token = $data->access_token;
		}
		
		return $access_token;
	}
	
	private function httpGet($url) {
		
    $curl = curl_init();
	
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
    
	curl_setopt($curl, CURLOPT_URL, $url);

    $res = curl_exec($curl);
    
	curl_close($curl);

    return $res;
  }
  
   private function get_php_file($filename) {
    
	return trim(substr(file_get_contents($filename), 15));//读取文件的内容
  
  }
  
  
   private function set_php_file($filename, $content) {//修改文件的内容
    
	$fp = fopen($filename, "w");
    
	fwrite($fp, "<?php exit();?>" . $content);
    
	fclose($fp);
  }
  
  
}

?>